package com.learn.criminalintent

import android.app.Dialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.widget.TimePicker
import androidx.fragment.app.DialogFragment
import java.util.Calendar
import java.util.Date

private const val ARG_TIME = "time"

class TimePickerFragment : DialogFragment() {

    interface CallBacks {
        fun onTimeSelected(date: Date)
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

        // 把日期发回给CrimeFragment
        // 第一个参数是指确定日期的DatePicker。这里不需要用它，所以用了一个_做名字。_表示不使用的参数，是一个Kotlin编码约定。
        val dateListener =
            TimePickerDialog.OnTimeSetListener { _: TimePicker, hourOfDay: Int, minute: Int ->
                val calendar = Calendar.getInstance()
                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
                calendar.set(Calendar.MINUTE, minute)
                val time = calendar.time
                targetFragment?.let { fragment ->
                    (fragment as CallBacks).onTimeSelected(time)
                }
            }

        val date: Date = arguments?.getSerializable(ARG_TIME) as Date

        val calendar = Calendar.getInstance()
        calendar.time = date

        val hourOfDay = calendar.get(Calendar.HOUR_OF_DAY)
        val minute = calendar.get(Calendar.MINUTE)


        return TimePickerDialog(
            requireContext(),
            dateListener,
            hourOfDay,
            minute,
            true
        )
    }

    companion object {
        fun newInstance(date: Date): TimePickerFragment {
            val args = Bundle().apply {
                putSerializable(ARG_TIME, date)
            }
            return TimePickerFragment().apply {
                arguments = args
            }
        }
    }
}